package code.structure.manager.loader
{
	import com.loadPackage.BulkErrorEvent;
	import com.loadPackage.BulkLoader;
	import com.loadPackage.BulkProgressEvent;
	import com.loadPackage.loadingtypes.LoadingItem;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;
	
	import code.main.AppData;
	import code.structure.manager.others.StatisticsManager;
	import code.structure.manager.sound.ISound;
	import code.structure.manager.sound.MySoundManager;
	import code.tools.gameIni.GameIniData;
	import code.tools.gameIni.LoadItem;
	import code.untils.LogConst;
	
	/**
	 * 加载内容控制管理器
	 * @author Yuri
	 * 
	 */
	public class DllLoaderManager
	{
		private static var _instance:DllLoaderManager;
		/**
		 *首次加载 
		 */
		private var _firstBLoader:BulkLoader;
		/**
		 *异步加载 
		 */
		private var _asyncBLoader:BulkLoader;
		/**
		 *异步第二个加载 
		 */
		private var _asyncTwoBLoader:BulkLoader;
		
		private var _swfAnalyer:SwfLoaderAnalyer;
		private var _imageAnalyer:ImageLoaderAnalyer;
		private var _xmlAndTextAnalyer:XmlAndTextLoaderAnalyer;
		
		/**
		 * 加载器字典 
		 */
		private var _bLoaderDic:Dictionary;
		
		private var _mainApplicationDomain:ApplicationDomain;
		/**
		 *人物加载器 
		 */
		private var _roleBLoader:BulkLoader;
		/**
		 *icon加载器 （登陆奖励等） 
		 */
		private var _iconBLoader:BulkLoader;
		public function DllLoaderManager()
		{
			if(_instance){ 
				throw new Error("实例化单例类出错-DllLoaderManager");
			}else{
				init();
			}
		}
		
		private function init():void{
			_firstBLoader = new BulkLoader("first_load");
			_asyncBLoader = new BulkLoader("async_load");
			_asyncTwoBLoader = new BulkLoader("async2_load");
			_roleBLoader = new BulkLoader("role_load");
			_iconBLoader = new BulkLoader("icon_load")
		}
		
		public static function getInstance():DllLoaderManager{
			if(!_instance) _instance = new DllLoaderManager();
			return _instance;
		}
		
		/************************************配置表文件加载处理*****************************************/
		
		/**
		 *加载loading 
		 * @param loadingcompleteFun
		 * 
		 */
		public function loadLoading(loadingcompleteFun:Function):void{
			var loadingItem:LoadingItem = _firstBLoader.add(GameIniData.loadingItem.path,getLoaderPro());
			loadingItem._id = GameIniData.loadingItem.name;
			loadingItem.addEventListener(Event.COMPLETE, onLoadingCompleteHandler);
			_firstBLoader.start();
			function onLoadingCompleteHandler(e:Event):void
			{
				var lItem:LoadingItem = e.currentTarget as LoadingItem;
				getAnalyer(lItem.type).setData(lItem);
				loadingcompleteFun.call();
			}
		}
		
		
		/**
		 *加载首次需要的文件 
		 * 为entry类使用 方便loading等
		 */
		public function loadFirstFiles(completeFun:Function,progressFun:Function,app:ApplicationDomain = null):void{
			_firstBLoader.clear();
			_firstBLoader  =new BulkLoader("first_load");
			var i:int;
			var firstLoadList:Array = GameIniData.getFirstLoadItemList(AppData.isNew);
			var count:int = firstLoadList.length;
			for (i = 0; i < count; i += 1 ) {
				var tempLItem:LoadItem = firstLoadList[i];
				var loadingItem:LoadingItem = _firstBLoader.add(tempLItem.path,getLoaderPro());
				loadingItem._id = tempLItem.name;
				loadingItem.addEventListener(Event.OPEN,onFirstFileLoaderItemStartHandler);
				loadingItem.addEventListener(Event.COMPLETE, onFirstFileLoaderItemCompleteHandler);
				loadingItem.addEventListener(BulkErrorEvent.ERROR,onFirsetFileLoaderItemErrorHandler);
			}
			_firstBLoader.addEventListener(BulkLoader.PROGRESS, onFirstLoadProgressHandler);
			_firstBLoader.addEventListener(BulkLoader.COMPLETE, onFirstLoadCompleteHandler);
			_firstBLoader.start();
			
			function onFirstFileLoaderItemStartHandler(e:Event):void{
				var sItem:LoadingItem = e.currentTarget as LoadingItem;
				firstFileLoadLog(1,sItem.url.url);
			}
			function onFirstFileLoaderItemCompleteHandler(e:Event):void{
				var lItem:LoadingItem = e.currentTarget as LoadingItem;
				getAnalyer(lItem.type).setData(lItem);
				firstFileLoadLog(2,lItem.url.url);
			}
			function onFirsetFileLoaderItemErrorHandler(e:BulkErrorEvent):void{
				var eItem : LoadingItem  = e.target as LoadingItem;
				firstFileLoadLog(3,eItem.url.url);
			}
			function onFirstLoadProgressHandler(e:BulkProgressEvent):void{
				progressFun.call(null,e._weightPercent);
			}
			function onFirstLoadCompleteHandler(e:Event):void{
				var mainM:MovieClip = _firstBLoader.getMovieClip("main");
				//_mainApplicationDomain =  mainM.loaderInfo.applicationDomain;
				completeFun.call(null,mainM);
				_firstBLoader.removeEventListener(BulkLoader.PROGRESS, onFirstLoadProgressHandler);
				_firstBLoader.removeEventListener(BulkLoader.COMPLETE, onFirstLoadCompleteHandler);
				loadSecondFiles();
			}
		}
		
		private function firstFileLoadLog(type:int,item:String = null):void
		{
			var date:Date = new Date();
			var d:String = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();
			if(d == AppData.firstFileLoadLogDate)
			{
				item = item.split('?')[0];
				item = item.split('/').pop();
				StatisticsManager.writeLog(LogConst.FIRST_FILE_LOAD,type,item);
			}
		}
		
		/**
		 *二次加载配置文件 
		 * 
		 */
		private function loadSecondFiles():void{
			var i:int;
			var count:int = GameIniData.secondLoadItemList.length;
			for (i = 0; i < count; i += 1 ) {
				var tempLItem:LoadItem = GameIniData.secondLoadItemList[i];
				var loadingItem:LoadingItem = _firstBLoader.add(tempLItem.path,getLoaderPro());
				loadingItem._id = tempLItem.name;
				loadingItem.addEventListener(Event.COMPLETE, onSecondFileLoaderItemCompleteHandler);
			}
			function onSecondFileLoaderItemCompleteHandler(e:Event):void{
				var lItem:LoadingItem = e.currentTarget as LoadingItem;
				if(lItem.id == "sound"){
					MySoundManager.soundMain = lItem.content as ISound;
				}else
					getAnalyer(lItem.type).setData(lItem);
			}
		}
		
		/*****************************************************************************/
		
		/**
		 * 获取素材信息 
		 * @param key 加载名称 xml中可见
		 * @param subKey
		 * @param callBackFun
		 * @param type
		 * @param loaderType
		 * @return 
		 * 
		 */
		public function getMaterial(key:String,subKey:String,callBackFun:Function=null,type:String = "swf",loaderType:int=1):*{
			var material:*;
			material = getSyncMaterial(key,subKey,type);
			if(material){
				if(callBackFun!=null){
					callBackFun.call(null,material,key+"&"+subKey);
				}
			}else{
				material = getAsyncMaterial(key,subKey,callBackFun,type,loaderType);
			}
			return material;
		}
		
		/**
		 *获取前台UI素材 
		 * @param key
		 * @param subKey
		 * @param callBackFun
		 * @param type
		 * @param loaderType
		 * @return 
		 * 
		 */
		public function getUIMaterial(key:String,subKey:String,callBackFun:Function=null,type:String = "swf",loaderType:int=5):*{
			var material:*;
			material =  getAnalyer(type).getData(key,subKey,callBackFun);
			if(material){
				/*if(callBackFun!=null){
				callBackFun.call(null,material,key+"&"+subKey);
				}*/
			}else{
				var path:String = key;
				if(GameIniData.uiDic[key]){
					var lI:LoadItem = GameIniData.uiDic[key];
					path = lI.path;
					type = lI.type;
				}
				loadFileItem(path,key,loaderType,type);
			}
			return material;
		}
		
		/**
		 *获取同步加载素材 
		 * @param key
		 * @param subKey
		 * @param type
		 * @return 
		 * 
		 */
		public function getSyncMaterial(key:String,subKey:String,type:String = "swf"):*{
			return getAnalyer(type).getData(key,subKey);
		}
		
		/**
		 *获取异步加载的素材 
		 * @param key
		 * @param subKey
		 * @param type
		 * @return 
		 * 
		 */
		public function getAsyncMaterial(key:String,subKey:String,callBackFun:Function,type:String = "swf",loaderType:int=1):*{
			var returnObj:* =  getAnalyer(type).getData(key,subKey,callBackFun);
			if(!returnObj){
				var item : LoadingItem = getLoadingItemByKey(key,false,loaderType);
				if(!item)
					loadFileItem(key,null,loaderType,type);
			}
			return returnObj;
		}
		
		/**
		 *是否这个key在加载中 
		 * @param key
		 * @return 
		 * 
		 */
		private function getLoadingItemByKey(key:String,isSync:Boolean=true,loaderType:int=1):LoadingItem{
			var item : LoadingItem;
			if(isSync){
				item = _firstBLoader.get(key);
			}else{
				item = getLoader(loaderType).get(key);
			}
			return item;
		}
		
		/**
		 *加载素材 
		 * @param loadItem
		 * 
		 */
		private function loadFileItem(path:String,id:String=null,loaderType:int=1,fileType:String=null):void{
			var loader:BulkLoader = getLoader(loaderType);
			var lItem:LoadingItem = loader.add(path,getLoaderPro(),fileType);
			id = id || path;
			lItem._id = id;
			lItem.addEventListener(Event.COMPLETE, onLoaderItemCompleteHandler);
			loader.start();
		}
		
		/**
		 *单个加载完成回调
		 * @param e
		 * 
		 */
		private function onLoaderItemCompleteHandler(e:Event):void{
			var lItem:LoadingItem = e.currentTarget as LoadingItem;
			getAnalyer(lItem.type).setData(lItem);
		}
		
		/**
		 *获取分析器 
		 * @param extension
		 * @return 
		 * 
		 */
		private function getAnalyer(extension:String):IAnalyer{
			var iAnalyer:IAnalyer;
			extension= extension.toLowerCase();
			if(extension == BulkLoader.TYPE_IMAGE || BulkLoader.IMAGE_EXTENSIONS.indexOf(extension) > -1){
				if(!_imageAnalyer){
					_imageAnalyer = new ImageLoaderAnalyer();
				}
				iAnalyer = _imageAnalyer;
			}else if (extension == BulkLoader.TYPE_SOUND ||BulkLoader.SOUND_EXTENSIONS.indexOf(extension) > -1){
				
			}else if (extension == BulkLoader.TYPE_VIDEO ||BulkLoader.VIDEO_EXTENSIONS.indexOf(extension) > -1){
				
			}else if (extension == BulkLoader.TYPE_TEXT || extension == BulkLoader.TYPE_XML ||BulkLoader.XML_EXTENSIONS.indexOf(extension) > -1 
				|| BulkLoader.TEXT_EXTENSIONS.indexOf(extension) > -1){
				if(!_xmlAndTextAnalyer){
					_xmlAndTextAnalyer = new XmlAndTextLoaderAnalyer();
				}
				iAnalyer = _xmlAndTextAnalyer;
			}else if (extension == BulkLoader.TYPE_MOVIECLIP ||BulkLoader.MOVIECLIP_EXTENSIONS.indexOf(extension) > -1){
				if(!_swfAnalyer){
					_swfAnalyer = new SwfLoaderAnalyer();
				}
				iAnalyer = _swfAnalyer;
			}
			return iAnalyer;
		}
		
		/**
		 *主体文件的域 
		 */
		public function set mainApplicationDomain(value:ApplicationDomain):void
		{
			_mainApplicationDomain = value;
		}
		
		private function getLoaderPro():Object{
			var props:Object = null;
			/*if(_mainApplicationDomain){
			props = {"context":new LoaderContext(true,_mainApplicationDomain)};
			}*/
			return props;
		}
		
		public function destroyMeterial():void{
			
		}
		
		/**
		 *获取加载器 
		 * @param loaderType
		 * @return 
		 * 
		 */
		private function getLoader(loaderType:int=1):BulkLoader{
			var loader:BulkLoader;
			switch(loaderType){
				case 0:
					loader = _firstBLoader;
					break;
				case 1:
					loader = _asyncBLoader;
					break;
				case 2:
					loader = _asyncTwoBLoader;
					break;
				case 3:
					loader =_roleBLoader;
					break;
				case 4:
					loader =_iconBLoader;
					break;
				default:
					if(!_bLoaderDic)_bLoaderDic = new Dictionary();
					if(!_bLoaderDic[loaderType])_bLoaderDic[loaderType] = new BulkLoader("loader_"+loaderType);
					loader = _bLoaderDic[loaderType] /*_asyncTwoBLoader*/;
					break;
			}
			return loader;
		}
		
	}
}